#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
1.导包
2.获取测试数据
3.定义一个测试类
    3.1创建测试用例方法
    3.2获取测试数据内进行请求所需要的关键字段
    3.3进行requests请求，获得返回结果
    3.4断言接口返回结果，判断成功失败
'''

#导包
import readExcle
import unittest
import requests
from ddt import ddt,data,unpack
import configHttp
import writeExcle

#实例化获取测试数据
data_obj = readExcle.ReadExcle()
#调用实例方法
test_data = data_obj.read()
#定义一个测试类
@ddt
class TestCase(unittest.TestCase):
    #创建测试用例方法
    @data(*test_data)
    @unpack
    # def test_case(self, id, interfaceUrl, name, method, value, expect, real, status):
    def test_case(self, id, interfaceUrl, name, method, value, expect, real, status):
        #获取测试数据内进行请求所需要的关键字段
        # id = test_data[i]['id']
        # value = eval(test_data[i]['value'])
        # url = test_data[i]['interfaceUrl']
        # expect = int(test_data[i]['expect'])
        # method = test_data[i]['method']
        value = eval(value)
        expect = int(expect)
        # if method == 'get':
        #     re = requests.get(url=interfaceUrl, params=value)
        #     # return re
        # elif method == 'post':
        #     re = requests.post(url=interfaceUrl, data=value)
        #     # return re
        result = configHttp.ConfigHttp(method, interfaceUrl, value)
        re = result.run()

        print(re.text)
        res_dict = re.json()


        #获取实际结果
        real = res_dict['errorCode']
        #获取状态
        # if real == expect:
        #     status = 'pass'
        # else:
        #     status = 'fail'
        # we = writeExcle.WriteExcle()
        # we.write_data(int(id), 6, real, status)
        # 断言接口返回结果，判断接口调用成功失败
        # self.assertEqual(res_dict['errorCode'], expect, '测试用例不通过')

        #断言坑一：
        #使用if进行判断时，需要手动跑出异常
        #会导致失败数据不会写入用例中，raise后面代码不会执行
        # if real == expect:
        #     status = 'pass'
        # else:
        #     status = 'fail'
        #     raise AssertionError('用例执行失败')
        # we = writeExcle.WriteExcle()
        # we.write_data(int(id), 6, real, status)

        #坑二：
        try:
            if real == expect:
                status = 'pass'
            else:
                status = 'fail'
            we = writeExcle.WriteExcle()
            we.write_data(int(id), 6, real, status)
            self.assertEqual(res_dict['errorCode'], expect, '测试用例不通过')
        except Exception as msg:
            print(f'异常：{msg}')
            raise


if __name__ == '__main__':
    unittest.main(verbosity=2)







